package com.lsfb.signsys.login;

import android.app.Application;
import android.support.annotation.NonNull;

import com.lsfb.signsys.ApiException;
import com.lsfb.signsys.compatible.Config;
import com.lsfb.signsys.utils.SPUtils;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * Created by zgscwjm on 2018/3/15.
 */

public class LoginPresenter implements LoginContract.Presenter {

    private final LoginContract.View mLoginView;

    /**
     * model层
     */
    private final LoginRepository mLoginRepository;

    private final CompositeDisposable mCompositeDisposable;

    public LoginPresenter(@NonNull LoginContract.View loginView) {

        //将视图层 绑定到 Presenter 层
        mLoginView = loginView;

        //设置model层
//        mLoginRepository = loginRepository;
        mLoginRepository = new LoginRepository();
//        Injection.provideTasksReposiotry();

        mCompositeDisposable = new CompositeDisposable();
//        将Prsenter 绑定到视图层
        mLoginView.setPresenter(this);
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mCompositeDisposable.clear();
    }

    @Override
    public void login(String username, String password) {

        mCompositeDisposable.clear();


        mLoginView.showLoad();
        //todo 用户名,密码的校验

        LoginTO loginTO = new LoginTO();
        loginTO.setUsername(username);
        loginTO.setPassword(password);


        Disposable disposable =

                mLoginRepository.login(loginTO).subscribe(loginBean -> {
                    Config.setUserId(loginBean.getUserid());
                }, e -> {
                    mLoginView.endLoad();
                    if (e instanceof ApiException) {
                        mLoginView.showMessage(((ApiException) e).getMsg());
                    } else {
                        mLoginView.showMessage("未知错误");
                    }
                }, () -> {

                    mLoginView.endLoad();
                    mLoginView.showMainActive();
                });


        mCompositeDisposable.add(disposable);
    }

    @Override
    public void forget() {
        mLoginView.showForgetPwdActive();
    }


}
